package conf

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"

	"github.com/spf13/viper"
)

var vconf_relative_path = ".ctt"

func LoadFile(file string) {
	fpath := filePath(file)

	// 读取文件
	s, err := os.ReadFile(fpath)
	if err != nil {
		panic(err)
	}

	// TODO: 支持.env文件

	viper.SetConfigType("yaml")
	err = viper.ReadConfig(bytes.NewBuffer(s))
	if err != nil {
		panic(err)
	}
}

// name 参数支持通过.分隔符来访问嵌套配置
func UnmarshalKey(name string, v any) error {
	return viper.UnmarshalKey(name, &v)
}

func UnmarshalKeyDefault(name string, v any, def any) {
	e := viper.UnmarshalKey(name, &v)
	if e != nil {
		v = def
	}
}

// 搜索文件
func filePath(file string) (fpath string) {
	// 可执行文件路径
	binPath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	fpath = filepath.Join(binPath, "../", vconf_relative_path, file)

	fmt.Println(">>> path=", fpath)
	if _, err := os.Stat(fpath); err == nil {
		return fpath
	}

	// 在项目路径
	wdPath, _ := os.Getwd()
	fpath = filepath.Join(wdPath, vconf_relative_path, file)
	fmt.Println(">>> path=", fpath)
	if _, err := os.Stat(fpath); err == nil {
		return fpath
	}

	return fpath
}
